package com.hengpeng.itfin.service.ehcache.impl;

import java.lang.reflect.Type;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import org.apache.commons.codec.binary.Base64;
import org.codehaus.jackson.map.type.TypeFactory;
import org.codehaus.jackson.type.JavaType;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import com.hengpeng.common.exception.GenericType;
import com.hengpeng.common.exception.ServiceResult;

public class EhchaceObserver implements Observer
{

	@Override
	public void update(Observable observable, Object ehcacheName)
	{

		if (null != ehcacheName)
		{
			// 请求客户端删除缓存
			doPostTrans("ehcacheClientUpdate", new GenericType<ServiceResult<Boolean>>()
			{
			}, ehcacheName.toString());
		}

	}

	@SuppressWarnings("unused")
	private <T> T doPostTrans(String transName, final GenericType<T> type, Object parameter, Object... pathValue)
	{
		HttpHeaders requestHeaders = createAuthHeaders();

		// 设置JSON转换器
		List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
		converters.add(new MappingJacksonHttpMessageConverter()
		{
			@Override
			protected JavaType getJavaType(Type typeInner, Class<?> contextClass)
			{
				return TypeFactory.type(type.getType());
			}

			//@Override
			protected JavaType getJavaType(Class<?> clazz)
			{
				return TypeFactory.type(type.getType());
			}
		});
		RestTemplate genericRestTemplate = new RestTemplate();
		genericRestTemplate.setMessageConverters(converters);

		HttpEntity<Object> entity = new HttpEntity<Object>(parameter, requestHeaders);
		return null;
		// return (T) genericRestTemplate.postForEntity(Configuration.getContent("PortServiceUrl") + transName, entity,
		// type.getType().getClass(), pathValue).getBody();
	}

	private HttpHeaders createAuthHeaders()
	{
		HttpHeaders requestHeaders = new HttpHeaders();
		// Authorization
		String userPassword = "pprun" + ":" + "pprunpprun";
		String encoding = new String(Base64.encodeBase64(userPassword.getBytes()), Charset.forName("UTF-8"));
		requestHeaders.set("Authorization", "Basic " + encoding);
		// Accept
		requestHeaders.set("Accept", "application/json");
		requestHeaders.set("Accept-Charset", "UTF-8");
		return requestHeaders;
	}

}